<?php
namespace app\admin\controller;

use think\Request;
use app\admin\model\Category as CategoryModel;

class Category extends Base
{
    protected $model;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        $this->model = new CategoryModel();
    }

    public function index()
    {
        $data = $this->model->where('is_del', 0)->select();

        $data = obj_tree($data);

        $this->assign("data", $data);

        return $this->fetch();
    }

    public function addOrEdit($id = 0)
    {
        if ($id != 0) {
            $data = $this->model->find($id);
        } else {
            $data = [
                'id' => 0,
                'pid' => 0,
                'name' => '',
                'tablename' => '',
                'onclick' => '',
                'note' => '',
                'sort' => 0
            ];
        }
        
        $data_all = $this->model->field('id, pid, name')->where('is_del', 0)->select();
        $data_all = obj_tree($data_all);
        
        $this->assign('data', $data);
        $this->assign('data_all', $data_all);
        return $this->fetch();
    }

    public function doAddOrEdit(Request $request = null, $id = 0)
    {
        if ($request->isPost()) {
            $param = $request->param();

            if ($param['name'] == '') {
                $this->error("栏目名不能为空");
            }

            try {
                if ($param['id'] != 0) {
                    $this->model->save([
                        'pid' => $param['pid'],
                        'name' => $param['name'],
                        'tablename' => $param['tablename'],
                        'onclick' => $param['onclick'],
                        'note' => $param['note'],
                        'sort' => $param['sort']
                    ], ['id' => $param['id']]);
                } else {
                    $this->model->save([
                        'pid' => $param['pid'],
                        'name' => $param['name'],
                        'tablename' => $param['tablename'],
                        'onclick' => $param['onclick'],
                        'note' => $param['note'],
                        'sort' => $param['sort'],
                        'create_time' => time()
                    ]);
                }
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                $this->error("错误提示:".$msg);
            }
            $this->success('操作成功', 'index');
        }
    }

    public function delete($id = null)
    {
        if (Request::instance()->isAjax()) {
            if ($this->model->where('pid', 'in', $id)->value('id')) {
                return ['code'=>0, 'msg'=>'子栏目不为空, 若要删除请先清空子栏目'];
            }

            if ($this->model->destroy($id)) {
                return ['code' => 1,'msg'=>"删除成功"];
            } else {
                return ['code' => 0,'msg'=>"删除失败"];
            }
        }
    }
}
